package one.bugu.android.demon.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.ToastUtils;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import one.bugu.android.demon.MyApplication;
import one.bugu.android.demon.R;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.StatusBarUtils;

/**
 * 绑定手机号
 */
@LKContentView(R.layout.bound_tel_activity)
public class BoundTelActivity extends MyBaseActivity {

    @LKInjectView(R.id.ll_bt_back)
    private LinearLayout ll_bt_back;

    @LKInjectView(R.id.et_tel_input)
    private EditText et_tel_input;

    @LKInjectView(R.id.et_bt_code)
    private EditText et_bt_code;

    @LKInjectView(R.id.tv_bt_get_code)
    private TextView tv_bt_get_code;

    /**
     * 登录按钮
     */
    @LKInjectView(R.id.tv_bt_login)
    private TextView tv_bt_login;

    /**
     * 手机号格式验证
     */
    String MATCH_PHONE_REGEX = "((13)|(14)|(15)|(17)|(18)|(19)|(16))\\d{9}$";

    /**
     * 点击获取验证码进入倒计时 60秒
     */
    private CountDownTimer mCountDownTimer = new CountDownTimer(60000, 1000) {
        @SuppressLint("SetTextI18n")
        @Override
        public void onTick(long l) {
            //显示倒计时
            tv_bt_get_code.setText((l / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            tv_bt_get_code.setEnabled(true);
            tv_bt_get_code.setText("获取验证码");
            tv_bt_get_code.setTextColor(Color.parseColor("#ff5965b0"));
        }
    };


    @Override
    protected void initView() {
        super.initView();
        //初始化协议按钮和获取验证码按钮
        tv_bt_get_code.setEnabled(false);
        tv_bt_get_code.setTextColor(Color.parseColor("#A9A9A9"));

        StatusBarUtils.getInstance().setStatusBar(this, null);
    }

    @Override
    protected void initData() {
        super.initData();

        MyApplication.addActivity(this);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //手机号编辑框监听事件
        et_tel_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //手机号为空 获取验证码不可点击
                if (et_tel_input.length() == 11 && tv_bt_get_code.getText().toString().equals("获取验证码")) {
                    tv_bt_get_code.setEnabled(true);
                    tv_bt_get_code.setTextColor(Color.parseColor("#ff5965b0"));
                } else {
                    tv_bt_get_code.setEnabled(false);
                    tv_bt_get_code.setTextColor(Color.parseColor("#A9A9A9"));
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //验证码输入框监听事件
        et_bt_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @SuppressLint("NewApi")
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                //验证码不为空 登录按钮方可点击
                if (et_bt_code.length() != 0) {
                    tv_bt_login.setSelected(true);
                    tv_bt_login.setEnabled(true);
                } else {
                    tv_bt_login.setSelected(false);
                    tv_bt_login.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        //返回按钮点击事件
        ll_bt_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //获取验证码点击事件
        tv_bt_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //验证手机号格式
                Pattern p = Pattern.compile(MATCH_PHONE_REGEX);
                final Matcher m = p.matcher(et_tel_input.getText().toString());
                //格式正确调用验证新老用户和获取验证码方法
                if (m.matches()) {
                    //获取验证码
                    getVerificationCodeFuction();
                } else {
                    Toast.makeText(BoundTelActivity.this, "请输入正确手机号", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //登录
        tv_bt_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //验证码为4位
                if (et_bt_code.getText().toString().length() < 4) {
                    ToastUtils.custom("验证码输入不合法");
                    return;
                }
                //验证手机号格式
                Pattern p = Pattern.compile(MATCH_PHONE_REGEX);
                final Matcher m = p.matcher(et_tel_input.getText().toString());
                //格式正确 调用登录方法
                if (m.matches()) {
                    login();
                } else {
                    Toast.makeText(BoundTelActivity.this, "请输入有效的手机号!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    /**
     * 获取验证码
     */
    public void getVerificationCodeFuction() {
        Map<String, String> map = new HashMap<>();
        map.put("userPhone", et_tel_input.getText().toString());
        map.put("modelType", "110");
        map.put("modelTypee", "1");
        LKUtil.getHttpManager().postBody(HttpConstant.GETYZM_URL, map, getVerificationCodeHanlder);
    }

    /**
     * 获取验证码网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> getVerificationCodeHanlder = new BaseHttpAsycResponceHandler<String>(true) {

        @Override
        public void onSuccess(String data) {
            super.onSuccess(data);
            //开始倒计时
            mCountDownTimer.start();
            tv_bt_get_code.setTextColor(Color.parseColor("#A9A9A9"));
            tv_bt_get_code.setEnabled(false);
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ToastUtils.custom(message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    /**
     * 登录
     */
    public void login() {
        String token = PreferencesUtil.getInstance().getString(this, Constant.TOKEN);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userPhone", et_tel_input.getText().toString().trim());
        map.put("mobileCaptcha", et_bt_code.getText().toString().trim());
        map.put("modelTypee", "1");
        LKUtil.getHttpManager().postBody(HttpConstant.BOUND_TEL, map, hanlder);
    }

    /**
     * 获取验证码网络请求
     */
    @SuppressLint("HandlerLeak")
    public BaseHttpAsycResponceHandler<String> hanlder = new BaseHttpAsycResponceHandler<String>(true) {

        @Override
        public void onSuccess(String data) {
            super.onSuccess(data);
            //记录为登录状态
            PreferencesUtil.getInstance().putBoolean(BoundTelActivity.this, Constant.IS_LOGIN, true);
            if (TextUtils.equals(data, "0")) {
                //直接跳转至农场首页
                IntentUtils.startAty(BoundTelActivity.this, WarnMainActivity.class);
            } else {
                //去填写邀请码
                IntentUtils.startAty(BoundTelActivity.this, InviteActivity.class);
            }
            MyApplication.finishAllActivity();
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            ToastUtils.custom(message);
        }

        @Override
        public void onError() {
            super.onError();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MyApplication.removeActivity(this);
    }
}
